// cap_key.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "cap_key.h"


HINSTANCE hInst;

BOOL WINAPI DllMain(HINSTANCE hInstance,ULONG What,LPVOID NotUsed)
{
	switch(What)
	{
	case DLL_PROCESS_ATTACH:
		hInst = hInstance;
		break;
	case DLL_PROCESS_DETACH:
		break;
	case DLL_THREAD_ATTACH:
		break;
	case DLL_THREAD_DETACH:
		break;
	}
	return 1;
}

#pragma data_seg("hookdata")
KeyHook* gThis = 0; //singleton
#pragma data_seg()
#pragma comment(linker,"/SECTION:hookdata,RWS")

LRESULT CALLBACK CallBack(int c,WPARAM w, LPARAM l)
{
	return gThis->DoOnEvent(c, w, l);
}

KeyHook::KeyHook()
{
	if(gThis) throw std::exception("KeyHook is a singleton");
	gThis = this;
	_hInst = hInst;
	_lastHook = 0;
}

KeyHook::~KeyHook()
{
	Uninstall();
}

void KeyHook::Install(int hookid)
{
	OutputDebugStringA("Install Hook handle: 0x");
	_lastHook = SetWindowsHookEx(hookid, CallBack, hInst, 0);
	char op[12] = {0};
	_itoa_s((int)_lastHook, op, 16);
	OutputDebugStringA(op);
	OutputDebugStringA("\n");
}

void KeyHook::Uninstall()
{
	if(!_lastHook) return;
	OutputDebugStringA("Uninstall Hook\n");
	UnhookWindowsHookEx(_lastHook);
}

LRESULT KeyHook::DoOnEvent(int c,WPARAM w, LPARAM l)
{
	//OutputDebugStringA("OnEvent\n");
	OnEvent(c, w, l);
	return CallNextHookEx(_lastHook, c, w, l);
}

